<template>
	<div class="container">
		<el-page-header @back="goback" content="新增养殖计划">
		</el-page-header>
		<el-form
		style="margin-top:20px;"
		    :model="ruleForm"
		    ref="ruleForm"
		    :rules="rules"
		    :label-position="labelPosition"
		    label-width="120px"
		    class="demo-ruleForm">
		    <el-row>
		        <el-col :span="12">
		            <el-form-item label="种苗名称：" prop="breedName">
						<el-select v-model="ruleForm.breedName" value-key="id"  placeholder="" style="width:300px">
						    <el-option v-for="item in breedNameList" :key="item.id" :label="item.name" :value="item.name">{{item.name}}</el-option>
						</el-select>
		            </el-form-item>
					<el-form-item label="养殖批号：" prop="batch">
					    <el-input placeholder="请输入" v-model="ruleForm.batch" style="width: 300px">
					        <template slot="append">
								<el-button @click="addBatch">自动生成</el-button>
					        </template>
					    </el-input>
					</el-form-item>
		        </el-col>
		        <el-col :span="10" style="margin-top: 20px;">
					<el-form-item label="品种名称：" prop="seedName">
					    <el-input
					        placeholder="请输入内容"
					        v-model="ruleForm.seedName"
					        style="width:300px"
					    ></el-input>
					</el-form-item>
					<el-form-item label="养殖日期：" prop="time">
					    <el-date-picker
					        v-model="ruleForm.time"
					        type="date"
					        value-format="yyyy-MM-dd"
					        placeholder="请选择"
					        style="width:300px"
					    ></el-date-picker>
					</el-form-item>
		        </el-col>
				<el-col :span="12" style="mmargin-top:0px;">
					<el-form-item label="养殖负责人：">
						<template>
							<el-select
		                        v-model="principal"
								@change="choosePrincipal"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in userList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="10" style="mmargin-top:0px;">
					<el-form-item label="关联产品：">
						<template>
							<el-select
				                v-model="productId"
								@change = "selectProduct"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in productList"
									:key="item.id"
									:label="item.title"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="基地：">
						<template>
							<el-select
								v-model="breedBase"
								@change="chooseBreedBase"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in baseList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="养殖区域：">
						<template>
							<el-select
								v-model="soil"
								@change="chooseSoil"
								value-key="id"
								style="width:300px"
								placeholder="请选择"
							>
								<el-option
									v-for="item in soilList"
									:key="item.id"
									:label="item.name"
									:value="item"
								></el-option>
							</el-select>
						</template>
					</el-form-item>
				</el-col>
				<el-col>
					<!-- <el-form-item label="编号类型：">
						<el-radio v-model="ruleForm.type" label="耳标" border>耳标</el-radio>
						<el-radio v-model="ruleForm.type" label="RFID" border>RFID</el-radio>
					</el-form-item> -->
					<el-form-item label="RFID：">
						<el-input placeholder="请输入" v-model="code" style="width: 300px">
						    <template slot="append">
						        <el-button @click="add">添加</el-button>
						    </template>
						</el-input>
						<el-upload
							class="upload-demo"
							ref="upload"
							accept=".txt"		
							action="https://jsonplaceholder.typicode.com/posts/"
							:before-upload="beforeUpload"		                         
							:default-file-list="this.fileList"
						  >
						  <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
						</el-upload>
						<!-- <el-button>模板下载</el-button> -->
					</el-form-item>
					<el-table
					    :data="tableData"
					    border
					    style="margin-top:20px;"
					    ref="multipleTable"
					    header-cell-class-name="table-header"
					>
					    <el-table-column prop="time" sortable label="导入时间"></el-table-column>
					    <el-table-column prop="type" sortable label="编号类型"></el-table-column>
					    <el-table-column prop="code" sortable label="编号"></el-table-column>
					    <el-table-column prop="sex" sortable label="性别">
							<template slot-scope="scope">
								<!-- <el-input v-model=""></el-input> -->
								<el-select v-model="scope.row.sex" placeholder="请选择">
								    <el-option
								      v-for="item in sexlist"
								      :key="item.value"
								      :label="item.value"
								      :value="item.value">
								    </el-option>
								  </el-select>
							</template>
						</el-table-column>
					    <el-table-column sortable label="绑定设备">
					        <template slot-scope="scope">
								<el-button type="text">点击绑定</el-button>
							</template>
					    </el-table-column>
					    <el-table-column label="操作" width="150" align="center">
					        <template slot-scope="scope">
								<el-button
								    type="text"
									style="color: red;"
								    @click="handleDelete(scope.$index, scope.row)"
								>删除</el-button>
					        </template>
					    </el-table-column>
					</el-table>
				</el-col>
		    </el-row>
			
		    <el-form-item class="footerFixed" label-width="0px">
		        <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
		        <el-button @click="goback">取消</el-button>
		    </el-form-item>
		</el-form>
	</div>
</template>

<script>
import { soil_findAllBase,breed_save,breed_findById,born_inCode,soil_findSoilByType,breed_update,soil_findByBaseId } from '@/request/breedApi';
import { user_findByAll,basesource_findByAll,model_crop_loadbind,plot_findByAll,products_findByAll } from '@/request/api';
	export default{
		data(){
			return{
				productId:'',
				fileList:'',
				code:"",
				principal:"",
				breedBase:"",
				soil:"",
				tableData:[],
				labelPosition:'right',
				ruleForm:{
					"batch":"",
					type:'RFID'
				},
				rules:{
					breedName: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					batch: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					seedName: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					time: [
					    { required: true, message: '不能为空', trigger: 'change' }
					],
					
					
				},
				typeList:[],
				breedNameList:[
					
				],
				userList:[],
				baseList:[],
				soilList:[],
				sexlist:[
					{value:"雌"},
					{value:"雄"}
				],
				productList:[]
			}
		},
		beforeCreate() {
			// 读取文件
			FileReader.prototype.reading = function ({encode} = pms) {
				let bytes = new Uint8Array(this.result);    //无符号整型数组
				let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
				return text;
			};
			/* 重写readAsBinaryString函数 */
			FileReader.prototype.readAsBinaryString = function (f) {
				if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
					this.onload = e => {  //在this.onload函数中，完成公共处理
						let rs = this.reading();
						// console.log(rs);
					};
				this.readAsArrayBuffer(f);  //内部会回调this.onload方法
			};
		},

		mounted() {
			this.init();
			this.init1()
		},
		methods:{
			selectProduct(ele){
				this.ruleForm.productId = ele.id
			},
			init1(){
				products_findByAll("").then((res)=>{
					this.productList = res.data
				})
			},
			beforeUpload(file){
				this.fileList = [file]
				this.read(file);
				return false
			},
			read(f) {
				let rd = new FileReader();
				rd.onload = e => {  
				//this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
					let cont = rd.reading({encode: 'GBK'});
					let  formerData = this.textData;
					
					if(formerData == "" || formerData == null || formerData == undefined){
						this.textData = cont
					}else{
						this.textData = formerData + cont;
					}
					this.textData = this.textData.split("\r\n")
					
					var d=new Date();
					var year=d.getFullYear();
					var month=change(d.getMonth()+1);
					var day=change(d.getDate());
					var hour=change(d.getHours());
					var minute=change(d.getMinutes());
					var second=change(d.getSeconds());
					function change(t){
						if(t<10){
						return "0"+t;
						}else{
						return t;
						}
					}
					var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
					if(this.ruleForm.type == "" || this.ruleForm.type == null ||  this.ruleForm.type == undefined){
						this.$notify({
							title: '提示',
							message: '请选择编号类型后重新导入',
							type: 'info',
							duration:1000
						});
					}else{
						console.log(this.textData)
						for(var i=1;i<this.textData.length;i++){
							console.log(this.textData[i])
							var params = {
								"time":time,
								"type":this.ruleForm.type,
								"code":this.textData[i],
								"sex":""
							}
							this.tableData.push(params);
						}
					}
					this.textData = ""
				};
				rd.readAsBinaryString(f);
			},
			
			init() {
				if (this.$route.query.id != undefined) {
					breed_findById(this.$route.query.id).then((res) => {
						this.ruleForm = res.data;
						this.principal = res.data.principalName;
						this.breedBase = res.data.breedBaseName;
						this.soil = res.data.soilName;
						this.tableData = res.data.breedDetailList;
					});
				}
				user_findByAll("").then((res) => {
					this.userList = res.data;
				});
				plot_findByAll("").then((res) => {
					this.baseList = res.data;
				});
				// soil_findSoilByType({"type":2}).then((res) => {
				// 	this.soilList = res.data;
				// });
				model_crop_loadbind("").then((res)=>{
					this.breedNameList = res.data
					
				})
				// basesource_findByAll("").then((res)=>{
				//     this.breedNameList = res.data
				// })
				
			},
			// 返回上一页
			goback(){
				this.$router.go(-1)
			},
			// 删除
			handleDelete(index,row){
				this.tableData.splice(index,1)
			},
			addBatch() {
				var d = new Date();
				var curr_date = d.getDate();
				var curr_month = d.getMonth() + 1; 
				var curr_year = d.getFullYear();
				String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
				String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
				var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
				this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
			},
			add() {
				if (this.code == "" || this.code == null) {
					this.$notify({
						title: '提示',
						message: '编号不能为空',
						type: 'info',
						duration:1000
					});
					return;
				}
				if (this.ruleForm.type == "" || this.ruleForm.type == null) {
					this.$notify({
						title: '提示',
						message: '编号类型不能为空',
						type: 'info',
						duration:1000
					});
					return;
				}
				var d=new Date();
				var year=d.getFullYear();
				var month=change(d.getMonth()+1);
				var day=change(d.getDate());
				var hour=change(d.getHours());
				var minute=change(d.getMinutes());
				var second=change(d.getSeconds());
				function change(t){
					if(t<10){
					return "0"+t;
					}else{
					return t;
					}
				}
				var time=year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;

				var params = {
					"time":time,
					"type":this.ruleForm.type,
					"code":this.code,
					"sex":""
				}
				this.tableData.push(params);

				this.code = "";
			},
			choosePrincipal(ele){
				this.ruleForm.principalId = ele.id;
				this.ruleForm.principalName = ele.name;
			},
			chooseBreedBase(ele) {
				this.ruleForm.breedBaseId = ele.id;
				this.ruleForm.breedBaseName = ele.name;
				soil_findByBaseId(`${ele.id}/2`).then((res)=>{
					this.soilList = res
				})
			},
			chooseSoil(ele) {
				this.ruleForm.soilId = ele.id;
				this.ruleForm.soilName = ele.name;
			},
			submitrule(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid){
						this.ruleForm.breedNumber = this.tableData.length;
						this.ruleForm.breedDetailList = this.tableData;
						if(this.$route.query.id == undefined){
							breed_save(this.ruleForm).then((res) => {
								if (res.code == 200) {
									this.$notify({
										title: '提示',
										message: '保存成功',
										type: 'success',
										duration:1000
									});
									this.goback()
								}
							});
						}else{
							breed_update(this.ruleForm).then((res)=>{
								if (res.code == 200) {
									this.$notify({
										title: '提示',
										message: '修改成功',
										type: 'success',
										duration:1000
									});
									this.goback()
								}
							})
						}
					}else{
						return false
					}
				})
			}
			
		}
	}
</script>

<style scoped lang="less">
	.upload-demo{
		display:inline-block;
		margin-left:20px;
	}

	/deep/.el-upload--text{
		width:80px;
		height:35px;
	}

	.el-button--primary{
		// color:black;
		// background:white;
		border-color:#DCDFE6;
	}
</style>
